package com.itheima.reggie.controller;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.gson.Gson;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.SMSUtils;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Description: // 类说明，在创建类时要填写
 * @ClassName: UserController    // 类名，会自动填充
 * @Author: MYH          // 创建者
 * @Date: 2022/12/18 15:05   // 时间
 * @Version: 1.0     // 版本
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 通过发送短信来获取验证码
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session) throws ClientException {
        //获取手机号
        String phone = user.getPhone();

        if (StringUtils.isNotEmpty(phone)){
            //生成随机的6为验证码
            String code = ValidateCodeUtils.generateValidateCode(6) + "";

            //输出验证码
            log.info("验证码为：{}",code);

            //调用阿里云提供的短信服务的API来完成发送短信
            //SMSUtils.sendMessage("瑞吉外卖","SMS_154950909",phone,code);
            SMSUtils.sendShortMessage(phone,code);

            //需要将生成的验证码保存到session，用于登录校验
            //session.setAttribute(phone,code);

            //将生成的验证码缓存到redis中，并设置有效期为1分钟。
            ValueOperations valueOperations = redisTemplate.opsForValue();
            valueOperations.set(phone,code,60l, TimeUnit.SECONDS);

            return R.success("手机验证码短信发送成功！！");
        }
        return R.error("手机验证码短信发送失败！！");
    }


    /**
     * 移动端用户登录
     * 注意：不能使用user对象接收，应该使用map集合来接收前端传来的数据，因为user对象里没有code属性
     * @param map
     * @param session
     * @return
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpSession session) {

        //输出日志
        log.info("手机号和验证码：{}",map);

        //获取手机号
        String phone = map.get("phone") + "";

        //获取验证码
        String code = map.get("code") + "";

        //从Session中获取保存的验证码
        //Object sessionCode = session.getAttribute(phone) ;

        //从redis中获取验证码
        ValueOperations valueOperations = redisTemplate.opsForValue();
        Object redisCode = valueOperations.get(phone);

        //进行验证码的校验(页面提交的验证码和session中获取的验证码)
        if (redisCode != null && redisCode.equals(code)){//如果能够校验成功，说明登录成功

            //判断当前手机号对应的用户是否为新用户，如果是，则自动完成注册
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone,phone);
            User user = userService.getOne(queryWrapper);
            if (user == null){//说明是新用户
                user = new User();
                user.setPhone(phone);//完成自动注册
                userService.save(user);
            }

            //将user_id放入到session当中去
            session.setAttribute("user",user.getId());

            //输出session
            log.info("输出session:{}",session.getAttribute("user"));

            //如果用户登录成功，则删除redis中缓存的验证码
            redisTemplate.delete(phone);

            return R.success(user);
        }
        return R.error("登录失败！！");
    }


    @PostMapping("/loginout")
    public R<String> logout(HttpSession session){

        //清理Session中保存的当前登录user_id
        session.removeAttribute("user");
        return R.success("退出成功！！");
    }
}
